import React, { useMemo, useRef, useState } from 'react';
import { Animated, ImageProps, ImageStyle, StyleProp, View, Image } from 'react-native';

type Props = {
  uri: string;
  thumbnailUri?: string;
  style?: StyleProp<ImageStyle>;
  onError?: ImageProps['onError'];
  onLoadEnd?: () => void;
};

const ProgressiveImage: React.FC<Props> = ({ uri, thumbnailUri, style, onError, onLoadEnd }) => {
  const mainOpacity = useRef(new Animated.Value(0)).current;
  const thumbOpacity = useRef(new Animated.Value(0)).current;
  const [showThumb, setShowThumb] = useState(Boolean(thumbnailUri));

  const mainSource = useMemo(() => ({ uri }), [uri]);
  const thumbSource = useMemo(() => (thumbnailUri ? { uri: thumbnailUri } : undefined), [thumbnailUri]);

  return (
    <View style={style}>
      {showThumb && thumbSource && (
        <Animated.Image
          source={thumbSource}
          style={[style as any, { position: 'absolute', width: '100%', height: '100%', opacity: thumbOpacity }]}
          blurRadius={4}
          onLoad={() => {
            Animated.timing(thumbOpacity, { toValue: 1, duration: 150, useNativeDriver: true }).start();
          }}
        />
      )}
      <Animated.Image
        source={mainSource}
        style={[style as any, { opacity: mainOpacity }]}
        onError={onError}
        onLoadEnd={() => {
          Animated.timing(mainOpacity, { toValue: 1, duration: 220, useNativeDriver: true }).start(() => {
            setShowThumb(false);
            onLoadEnd && onLoadEnd();
          });
        }}
        resizeMode="cover"
      />
    </View>
  );
};

export default ProgressiveImage;

